import { useChatDataStore } from "@/store";
import { useChatScroll } from "./useChatScroll";

// 重新生成相关逻辑
export function useChatRegenerate() {
  const chatDataStore = useChatDataStore();
  const regenerateChatNewIndex = ref(1);

  // 切换助手历史记录
  const toggleAssistantHistoryChat = (
    index: number,
    direction: "prev" | "next"
  ) => {
    const { scrollToBottom } = useChatScroll();
    const chatWin = chatDataStore.chatHistoryWin[index];
    const regenerateChat = chatWin.regenerateChat || [];
    // 边界检查：至少需要2条才能切换
    if (regenerateChat.length <= 1) return;

    // 当前索引优先使用 regenerateChatNewIndex
    let currentIndex = regenerateChatNewIndex.value;

    // 确保索引在合法范围内（0 ≤ index < length）
    currentIndex = Math.max(
      0,
      Math.min(currentIndex, regenerateChat.length - 1)
    );

    // 计算新索引
    const newIndex = direction === "prev" ? currentIndex - 1 : currentIndex + 1;

    // 严格边界检查
    if (newIndex < 0 || newIndex >= regenerateChat.length) return;

    const newMessage = regenerateChat[newIndex];
    // 更新数据
    chatDataStore.chatHistoryWin[index] = {
      ...chatWin,
      ...newMessage, // 直接展开新消息属性
      regenerateChat, // 保留历史记录
    };

    // 必须更新索引状态
    regenerateChatNewIndex.value = newIndex;
    scrollToBottom();
    console.log(`切换成功：${currentIndex} → ${newIndex}`);
  };

  return {
    regenerateChatNewIndex,
    toggleAssistantHistoryChat,
  };
}
